package com.learn.springboot.util;

import com.learn.springboot.exception.ValidException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Objects;
import java.util.Set;

/**
 * 验证 Util
 *
 * @author Don
 * @date 2020/07/08
 */
public class ValidateUtil {

    public static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();

    public static <T> void validate(T object) {
        Set<ConstraintViolation<T>> constraintViolations = VALIDATOR.validate(object);
        for (ConstraintViolation<T> constraintViolation : constraintViolations) {
            if (Objects.nonNull(constraintViolation)) {
                throw new ValidException(constraintViolation.getMessage());
            }
        }
    }
}
